package com.xishu.service;


import com.xishu.entity.shop.Shop;
import com.xishu.entity.shop.TakeOutSetting;
import com.xishu.util.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;

public class TakeOutSettingService implements Tools {
    private static Logger logger = LoggerFactory.getLogger(TakeOutSettingService.class);
    private static TakeOutSettingService instance = new TakeOutSettingService();

    private TakeOutSettingService() {
    }

    public static TakeOutSettingService getInstance() {
        return instance;
    }

    /**
     * 通过ID查询
     *
     * @param id
     * @return
     */
    public TakeOutSetting findById(Long id) throws Exception {
        return CommonService.getInstance().findEntity(id, TakeOutSetting.class);
    }

    /**
     * 查询分店下面的外卖设置，保证有一个唯一的外卖设定
     *
     * @param shopId
     * @return
     */
    public List<TakeOutSetting> findTakeAwaySetting(Long shopId) throws Exception {
        Object lock = LockService.getInstance().getLock("take.out.setting." + shopId);
        synchronized (lock) {
            List<TakeOutSetting> takeOutSettingList = ShopService.getInstance().findEntityListByShopId(shopId, TakeOutSetting.class);

            logger.info("take out setting size is {}", takeOutSettingList.size());

            if (takeOutSettingList.stream().filter(p -> getBoolean(p.getDefaultSetting())).findAny().isPresent()) {
                return takeOutSettingList;
            }

            logger.info("will create default take out setting {}", shopId);
            TakeOutSetting defaultTakeOutSetting = createDefaultTakeOutSetting(shopId);
            takeOutSettingList.add(defaultTakeOutSetting);
            return takeOutSettingList;
        }
    }

    /**
     * 创建默认的支付方式
     *
     * @param shopId
     */
    public TakeOutSetting createDefaultTakeOutSetting(Long shopId) throws Exception {
        TakeOutSetting takeOutSetting = new TakeOutSetting();
        Shop shop = ShopService.getInstance().findShopById(shopId);
        takeOutSetting.setCompanyId(shop.getCompanyId());
        takeOutSetting.setShopId(shopId);
        takeOutSetting.setDefaultSetting(true);
        takeOutSetting.setName_zh("外賣設定");
        takeOutSetting.setName_en("Take-away Settings");
        takeOutSetting.setEnablePayType(false);
        CommonService.getInstance().createObject(takeOutSetting);

        return takeOutSetting;
    }

}
